package com.tcdp.daos;

import java.util.List;

import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.ParameterExpression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import com.tcdp.models.BlogPostComment;

public class BlogPostCommentDao extends AbstractDao {

	public BlogPostComment findByKey(int id) {
		BlogPostComment blogPostComment = em.find(BlogPostComment.class, id);
		return blogPostComment;
	}

	public List<BlogPostComment> retrieveCommentByBlogPostId(int id) {
		CriteriaBuilder cb = em.getCriteriaBuilder();
		CriteriaQuery<BlogPostComment> cq = cb
				.createQuery(BlogPostComment.class);
		Root<BlogPostComment> root = cq.from(BlogPostComment.class);
		ParameterExpression<String> param = cb.parameter(String.class,
				"blogPostId");

		Predicate criteria = cb.and(cb.equal(root.get("blogPost")
				.<Integer> get("blogPostId"), param), (cb.isNull(root
				.get("blogPostCommentParent"))));
		cq.select(root).where(criteria);

		TypedQuery<BlogPostComment> tq = em.createQuery(cq);
		tq.setParameter("blogPostId", id);

		List<BlogPostComment> comments = tq.getResultList();
		return comments;
	}

	public boolean insertBlogPostComment(BlogPostComment comment) {

		try {
			
			BlogPostComment parent = comment.getBlogPostCommentParent();
			
			tx.begin();
			em.persist(comment);
			em.flush();
			em.clear();
//			em.refresh(comment);
			tx.commit();
			
			if(parent!=null){
				em.refresh(em.merge(parent));
			}
			
			
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			tx.rollback();
			return false;
		} finally {
			em.close();
		}
	}

}
